package com.haiertvbic.tvnow.network;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Xml;

import com.haiertvbic.tvnow.db.DbAdapter;
import com.haiertvbic.tvnow.db.InitAppDataBase;
import com.haiertvbic.tvnow.model.ChannelLogoBean;
import com.haiertvbic.tvnow.model.ChannelPIPBean;
import com.haiertvbic.tvnow.model.ProgramBean;
import com.haiertvbic.tvnow.model.ProgramItemBean;
import com.haiertvbic.tvnow.model.ProgramStateCache;
import com.haiertvbic.tvnow.util.Constant;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.widget.PIPUrlBean;

/**
 * @author sun 增加了图片获取，和台标获取
 */
public class EPGWeb {
	private static final String TAG = "EPGWeb";
	private static String url = Constant.DEFAULT_URL;
	// 获得频道截图的路径->url
	// get channel screenshot url
	private static String url_image_xml = Constant.IMAGE_URL;
	private static int week;
	private static boolean flag = true; // 保证读完一个台的数据在读一个台的数据

	// private static String pro_detail =
	// "http://122.70.151.105:8080/epgpic/default.jpg";//默认节目详情的图片路径

	/**
	 * 获取指定频道下的节目列表,于2012-9-29日做了节目属性的过滤，用户只能看到过滤后的
	 * 
	 * @param context
	 *            调用此方法的上下文
	 * @param channel_id
	 *            为int值得频道编号
	 * @return 返回一个台的所有节目,如果得不到数据就告知界面无法节目
	 * @throws Exception
	 */
	public static ArrayList<ProgramBean> getProgramList(Context context,
			int channel_id) {
//		http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=服务授权码&sid=随机会话编号&devmac=md5mac&devtype=设备类型号&epgflag=5&ctype=1&cid=46&epic=0&type=day&value=2
		Map<String, String> parmas = new HashMap<String, String>();
		// 频道号
		parmas.put("serviceno", "4040");
		parmas.put("serviceauth", "haiertv");
		parmas.put("sid", "123456");
		parmas.put("devmac", "md5mac");
		parmas.put("devtype", "DC18F0M0200A");
		parmas.put("epgflag", "5");
		parmas.put("ctype", 1 + "");
		parmas.put("cid", channel_id + "");
		parmas.put("epic", 0 + "");// 表示不要默认界面图片2013-2-19日加
		parmas.put("type","day");
		parmas.put("value", 2+ "");

		// 只获取当天的节目去掉其他周
		Calendar c = Calendar.getInstance();
		// 得到当前是周几
		week = c.getTime().getDay();
		if (week == 0) {
			week = 7;
		}
		// 初始化DB
		InitAppDataBase initAppDataBase = new InitAppDataBase();
		if (!initAppDataBase.isDBExist(context)) {
			SLog.d(TAG, "initAppDataBase-----数据库不存在---copyDBFile");
			initAppDataBase.copyDBFile(context);
		} else {
			SLog.d(TAG, "initAppDataBase-----数据库已存在");
		}

		SLog.d(TAG, "当前系统的周数=========" + week);
		return getProgramsByChannelId(context, parmas,
				String.valueOf(channel_id), String.valueOf(week));
	}

	/**
	 * 按节目查找其他播放频道及时间、集数等
	 * 
	 * @param context
	 *            调用此方法的上下文
	 * @param pid
	 *            节目的唯一标识, test 125,73085，181
	 * @param code
	 *            地区的代码 test1
	 * @return ArrayList<ProgramBean> 返回一个节目在其他台播放情况，如果没有数据就告知界面无法获取数据
	 * @throws Exception
	 */
	public static ArrayList<ProgramBean> getSituation(Context context,
			String pid, String code)  {
		
//		http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=服务授权码&sid=随机会话编号&devmac=md5mac&devtype=设备类型号&searchtype=4&fid=be4c17002fac911b106c3e7242cd9622&locid=1&type=day&value=2
		Map<String, String> parmas = new HashMap<String, String>();

		parmas.put("serviceno", "4040");
		parmas.put("serviceauth", "haiertv");
		parmas.put("sid", "123456");
		parmas.put("devmac", "md5mac");
		parmas.put("devtype", "DC18F0M0200A");
		parmas.put("searchtype", "4");
		parmas.put("fid", pid);// 125,73085
		parmas.put("locid", code);// 1
		parmas.put("type","day");
		parmas.put("value", 2+ "");
		SLog.d(TAG, "带过来的本地码是==========" + code);

		// 只获取当天的节目去掉其他周
		Calendar c = Calendar.getInstance();
		// 得到当前是周几
		week = c.getTime().getDay();
		if (week == 0) {
			week = 7;
		}
		SLog.d(TAG, "当前系统的周数=========" + week);
		return programTimeFilters(getformNET2(context, pid, parmas));
		// 根据节目唯一标志从数据库得倒节目
//		return getProgramsByPid(context, String.valueOf(pid), parmas,
//				String.valueOf(week));
	}

	/**
	 * 得倒节目的类型，这段程序由其他程序或代码段开启（比如广播），测试时可直接调用 用于得倒电视聚等四种符合标准的节目
	 * 
	 * @return ItemProgramBean类型集合，
	 */
	public static ArrayList<ProgramItemBean> getProgramItem(Context context) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=服务授权码&sid=随机会话编号&devmac=md5mac&devtype=设备类型号&searchtype=12
		Map<String, String> parmas = new HashMap<String, String>();

		parmas.put("serviceno", "4040");
		parmas.put("serviceauth", "haiertv");
		parmas.put("sid", "123456");
		parmas.put("devmac", "md5mac");
		parmas.put("devtype", "DC18F0M0200A");
		parmas.put("searchtype", "12");
		// 初始化DB
		InitAppDataBase initAppDataBase = new InitAppDataBase();
		if (!initAppDataBase.isDBExist(context)) {
			SLog.d(TAG, "initAppDataBase-----数据库不存在---copyDBFile");
			initAppDataBase.copyDBFile(context);
		} else {
			SLog.d(TAG, "initAppDataBase-----数据库已存在");
		}
		return getItems(context, parmas);
	}

	/**
	 * 得倒频道的当前节目和下一个节目
	 * 
	 * @param context
	 * @param cid
	 * @return
	 */
	public static ProgramBean getCurrentProgram(Context context, String cid) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=haiertv&sid=123456&devmac=123456&devtype=DC18F0M0200A&searchtype=11&cid=频道id

		ArrayList<ProgramBean> p = new ArrayList<ProgramBean>();

		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "4040");
		parmas.put("serviceauth", "haiertv");
		parmas.put("sid", "123456");
		parmas.put("devmac", "123456");
		parmas.put("devtype", "DC18F0M0200A");
		parmas.put("searchtype", "11");
		parmas.put("cid", cid);

		WebData cloudData = new WebData();
		InputStream result = null;
		// 获得XML数据流
		if (cloudData.getNetworkInfo(context)) {
			result = cloudData.PostDataStream(url, parmas);
		}
		if (result != null) {
			p = paserProgram(result);
			SLog.d(TAG, "当前节目的长度" + p.size());
		}
		if (p != null && p.size() > 0) {
			return p.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 得倒频道的台标，初始化数据时调用 调用方得倒的是ChannelLogoBean类型的集合，包含频道号，图片，图片路径等
	 * 
	 * @param context
	 * @param channel_id
	 *            :频道号集合
	 * @return
	 */
	/**
	 * get the channel logo
	 * 
	 * @param context
	 * @param channel_id
	 *            :the channel logo's cids
	 * @return 返回为null，主要就是为全局的软连接赋值，没有做缓存
	 */
	public static ArrayList<ChannelLogoBean> getChannelLogoXML(
			final Context context, String channel_id) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?searchtype=14&channelID=46@44@43@5@1

		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("searchtype", "14");
		parmas.put("channelID", channel_id);

		// 初始化DB
		InitAppDataBase initAppDataBase = new InitAppDataBase();
		if (!initAppDataBase.isDBExist(context)) {
			SLog.d(TAG, "initAppDataBase-----数据库不存在---copyDBFile");
			initAppDataBase.copyDBFile(context);
		} else {
			SLog.d(TAG, "initAppDataBase-----数据库已存在");
		}

		ArrayList<ChannelLogoBean> logo_xml = null;
		DbAdapter dbAdapter = DbAdapter.getInstance(context);
		Cursor cursor = dbAdapter.findLogoByChannelId(channel_id);
		if (cursor != null && cursor.getCount() > 0) {
			logo_xml = getLogoDataFromDB(cursor);
		} else {
			WebData cloudData = new WebData();
			InputStream result = null;
			if (cloudData.getNetworkInfo(context)) {
				result = cloudData.PostDataStream(url, parmas);
			}
			if (result != null) {
				logo_xml = paserChannelLogo(result);
				final ArrayList<ChannelLogoBean> logos = null;
			}
		}
		return logo_xml;
	}

	// 根据时间和频道号得节目

	/**
	 * 从网络获取节目数据，并将其存储在本地数据库；用于频道下的节目
	 * 
	 * @param context
	 * @param channel_id
	 * @param parmas
	 * @return
	 */
	private static ArrayList<ProgramBean> getformNET(final Context context,
			final String channel_id, Map<String, String> parmas) {

		WebData cloudData = new WebData();
		InputStream result = null;

		SLog.d(TAG, "httpurl===" + url);
		if (WebData.getNetworkInfo(context)) {
			SLog.d(TAG, "从网络获取节目数据!!");
			result = cloudData.PostDataStream(url, parmas);
		}
		ArrayList<ProgramBean> programs = new ArrayList<ProgramBean>();
		if (result != null) {
			programs = paserProgram(result);
			programs = programAttriFilters(context, programs);
			DbAdapter.getInstance(context).addProgram(
					programs);
			SLog.i(TAG,
					"节目标识为" + channel_id + "节目全部存到了数据库，长度为："
							+ programs.size());

		}
		return programs;
	}

	/**
	 * 从网络获取节目数据，并将其存储在本地数据库；用于节目在其他频道下的情况
	 * 
	 * @param context
	 * @param pid
	 * @param parmas
	 * @return
	 */
	private static ArrayList<ProgramBean> getformNET2(final Context context,
			final String pid, Map<String, String> parmas) {

		WebData cloudData = new WebData();
		InputStream result = null;

		SLog.d(TAG, "httpurl===" + url);
		if (WebData.getNetworkInfo(context)) {
			SLog.d(TAG, "从网络获取节目数据!!");
			result = cloudData.PostDataStream(url, parmas);
		}
		ArrayList<ProgramBean> programs = new ArrayList<ProgramBean>();
		if (result != null) {
			programs = paserProgram(result);
			// 存储到本地数据库中是按属性过滤后的值，存储的条件是已存储五个频道的数据；
//			if (ProgramStateCache.getsize() == Constant.CHANNEL_NUMBER) {
//				final ArrayList<ProgramBean> programfromPID;
//				programfromPID = programAttriFilters(context, programs);
//				new Thread() {
//					public void run() {
//						DbAdapter.getInstance(context).addProgram(
//								programfromPID);
//						SLog.i(TAG, "节目标识为" + pid + "节目全部存到了数据库，长度为："
//								+ programfromPID.size());
//						ProgramStateCache.setPid(pid);
//					};
//				}.start();
//
//			}
//			programs = programAttriFilters(context, programs);
		}
		return programs;
	}

	// 根据时间和频道号得节目

	/**
	 * get channel's screenshot
	 * 
	 * @param context
	 * @param channel_id
	 * @param count
	 *            ：the count that need
	 * @return
	 */
	/**
	 * 得倒频道下的截图,选择这个频道时调用，
	 * 
	 * @param context
	 * @param channel_id
	 * @param count
	 *            所需图片个数
	 * @return 返回该频道的截图 ，是做了缓存的,如果没取到返回
	 */
	public static ArrayList<PIPUrlBean> getChannelPIPXML(Context context,
			String channel_id, int count) {
		// http://tv.haieross.com/haier_ci_service?serviceno=7000&serviceauth=服务授权码&sid=随机会话编号&devmac=md5mac&devtype=设备类型号&NUM=6&channelID=6
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "7000");
		parmas.put("serviceauth", "haiertv");
		parmas.put("sid", "123456");
		parmas.put("devmac", "md5mac");
		parmas.put("devtype", "DC18F0M0200A");
		parmas.put("NUM", count + "");
		// 频道号
		parmas.put("channelID", channel_id);

		WebData cloudData = new WebData();
		InputStream result = null;
		ArrayList<ChannelPIPBean> bit_pics = new ArrayList<ChannelPIPBean>();
		ArrayList<PIPUrlBean> pipurls = new ArrayList<PIPUrlBean>();
		Map<String, SoftReference<Bitmap>> url_bm = new HashMap<String, SoftReference<Bitmap>>();
		SLog.d(TAG, "从网络获取频道图片数据!!");
		if (WebData.getNetworkInfo(context)) {
			result = cloudData.PostDataStream(url_image_xml, parmas);
		}
		if (result != null) {
			bit_pics = paserChannelPIP(result);
			for (int i = 0; i < bit_pics.size(); i++) {
				PIPUrlBean pipurl = new PIPUrlBean();
				pipurl.setCid(channel_id);
				// 请求图片的路径
				String str = bit_pics.get(i).getBitmap_url();
				pipurl.setPipUrl(str);
				// http://119.57.11.44/haierFileServer/ShowPicServlet?url=/20130116/1358325463812.png&type=small&width=400
				// str = str +"&width=384";//电视屏幕的1/5,高清768
				str = str + "&width=768";
				// str =
				// "http://pic10.nipic.com/20101029/3320946_134815429000_2.jpg";
				SLog.d(TAG, "频道" + channel_id + "第" + i + "个截图的url" + str);
				if (url_bm.containsKey(str) && url_bm.get(str).get() != null) {
					pipurl.setBm(url_bm.get(str).get());
				} else {
					Bitmap bitmap = WebData.getPicData(str);
					if (bitmap != null) {
						url_bm.put(str, new SoftReference<Bitmap>(bitmap));
						pipurl.setBm(bitmap);
					}
				}
				// 如果解析出来的图片是空的，就不保存
				if (channel_id != null && str != null && pipurl.getBm() != null) {
					pipurls.add(pipurl);
				}
			}
		}
		if (pipurls != null) {
			return pipurls;
		} else {
			return null;
		}
	}

	/**
	 * 根据URL获取图片：先根据URL中图片的文件名获取本地，若本地没有则根据URL获取网络
	 * 
	 * @param urlString
	 * @return
	 */
	public static Bitmap getBitmapFromURL(Context context, String urlString) {
		Bitmap bm = null;
		String[] s = urlString.split("/");
		String path = Constant.CACHE_DIR + s[s.length - 1];
		File mfile = new File(path);
		if (mfile.exists()) { // 若该文件存在
			bm = BitmapFactory.decodeFile(path);
			SLog.d(TAG, "===========" + path);
		} else {
			if (WebData.getNetworkInfo(context)) {
				bm = WebData.getPicData(urlString);
				if (bm != null) {
					saveCache(bm, path);
				}
			}
		}
		return bm;
	}

	/**
	 * 将图片保存到SD卡
	 * 
	 * @param bm
	 * @param filename
	 */
	private static void saveCache(Bitmap bm, String filename) {
		SLog.d(TAG, "文件名为=====" + filename);
		try {
			File myCaptureFile = new File(filename);
			BufferedOutputStream bos;
			bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
			bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			if (e != null) {
				SLog.e(TAG, e.getMessage());
			}
		} catch (IOException e) {
			if (e != null) {
				SLog.e(TAG, "-------" + e.getMessage());
			}
		}

	}

	// 如果存储卡存在，在存储卡创建目录/mnt/sdcard/Haier-iPG-TV-Companion/
	public static void initSdcarDir(Context context) {
		// 判斷sd card是否存在
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			// 获取SD卡目录
			File sdcardDir = Environment.getExternalStorageDirectory();

			File baseDir = new File(sdcardDir + "/com.haiertvbic.tvnow/");
			Constant.BASE_DIR = baseDir.getPath() + "/"; // 得到目录

			if (!baseDir.exists()) {
				baseDir.mkdir(); // 创建目录
			}

			File bookCoversDir = new File(Constant.BASE_DIR + "cache");
			Constant.CACHE_DIR = bookCoversDir.getPath() + "/";

			if (!bookCoversDir.exists()) {
				bookCoversDir.mkdir();
			}

			// 插入默认图片
			// Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
			// R.drawable.ic_launcher);
			// File imgPath = new File(Constant.CACHE_DIR + "default");
			// try {
			// FileOutputStream fos = new FileOutputStream(new
			// File(imgPath.getPath() + ".jpg"));
			// ByteArrayOutputStream bos = new ByteArrayOutputStream();
			// bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
			// fos.write(bos.toByteArray());
			// bos.close();
			// fos.close();
			// } catch (FileNotFoundException e) {
			// SLog.e("", e.toString());
			// } catch (IOException e) {
			// SLog.e("", e.toString());
			// }
		}
	}

	// 根据时间和频道号得节目

	/**
	 * 
	 * @param context
	 * @param parmas
	 * @return
	 */
	private static ArrayList<ProgramItemBean> getItems(final Context context,
			Map<String, String> parmas) {
		ArrayList<ProgramItemBean> items = new ArrayList<ProgramItemBean>();
		DbAdapter dbAdapter = DbAdapter.getInstance(context);
		Cursor cursor = dbAdapter.findAllItem();
		ProgramItemBean item = null;
		if (cursor != null && cursor.getCount() > 0) {
			SLog.i(TAG, "从本地取节目分类数据--------------------------");
			while (cursor.moveToNext()) {
				item = new ProgramItemBean();
				item.setNode(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.ITEM_NODE)));
				item.setName(cursor.getString(cursor
						.getColumnIndex(DbAdapter.ITEM_NAME)));
				item.setPnode(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.ITEM_PNODE)));
				items.add(item);
			}
			cursor.close();
		} else {
			WebData cloudData = new WebData();
			InputStream result = null;
			SLog.d(TAG, "从网络获节目分类数据!!");
			result = cloudData.PostDataStream(url, parmas);
			if (result != null) {
				// 解析后的分类数据
				items = paserProgramItem(result);
				// 将得倒的节目数据存到数据库
				DbAdapter.getInstance(context).addItem(items);
				SLog.i(TAG, "===============节目分类存到db中完成,共" + items.size() + "条");
//				new Thread(new Runnable() {
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//
//					}
//				}).start();

			}
		}

		return items;
	}

	/**
	 * 根据频道id得倒数据库中的节目数据，在查找的时候直接删除了当前时间以下的节目
	 * 
	 * @param context
	 * @param cid
	 * @return
	 */
	private static ArrayList<ProgramBean> getProgramsByChannelId(
			Context context, Map<String, String> parmas, String cid, String week) {
		SLog.i(TAG, "从本地数据库判断是否有节目数据--------------------------");
		DbAdapter dbAdapter = DbAdapter.getInstance(context);
		// 此时得倒的节目就是当前时间以下的
		Cursor cursor = dbAdapter.findProByChannelId(cid, week);
		ArrayList<ProgramBean> programs = new ArrayList<ProgramBean>() ;
		if (cursor != null && cursor.getCount() > 0) {
			programs= getDataFromDB(cursor);
		} else {
			getformNET(context, cid, parmas);
			cursor = 	dbAdapter.findProByChannelId(cid, week);
			if (cursor != null && cursor.getCount() > 0) {
				programs= getDataFromDB(cursor);
			}
//			return programTimeFilters(getformNET(context, cid, parmas));
		}
		return programs;
	}

	// 根据时间和频道号得节目

	private static ArrayList<ChannelLogoBean> getLogoDataFromDB(Cursor cursor) {

		ArrayList<ChannelLogoBean> logos = new ArrayList<ChannelLogoBean>();
		ChannelLogoBean logo = null;
		while (cursor.moveToNext()) {
			logo = new ChannelLogoBean();
			logo.setCid(cursor.getString(cursor.getColumnIndex(DbAdapter.CNAME)));
			logo.setCname(cursor.getString(cursor.getColumnIndex(DbAdapter.CID)));
			logo.setLogourl(cursor.getString(cursor
					.getColumnIndex(DbAdapter.LOGORUL)));
			logos.add(logo);
		}
		cursor.close();
		return logos;
	}

	private static ArrayList<ProgramBean> getDataFromDB(Cursor cursor) {
		ArrayList<ProgramBean> programs = new ArrayList<ProgramBean>();
		ProgramBean program = null;
		while (cursor.moveToNext()) {
			program = new ProgramBean();
			program.setPid(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_PID)));
			program.setPweekday(cursor.getInt(cursor
					.getColumnIndex(DbAdapter.PROGRAM_PWEEKDAY)));
			program.setPstime(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_PSTIME)));
			program.setPftime(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_PFTIME)));
			program.setPn(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_PN)));
			program.setEpgid(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_EPGID)));
			program.setCid(cursor.getInt(cursor
					.getColumnIndex(DbAdapter.PROGRAM_CID)));
			program.setCname(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_CNAME)));
			program.setPtype(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_PTYPE)));
			program.setPrecommend(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_PRECOMMENT)));
			program.setPicurl(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PICURL)));
			program.setFid(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_FID)));
			program.setFid2(cursor.getString(cursor
					.getColumnIndex(DbAdapter.PROGRAM_FID2)));

			programs.add(program);
		}
		cursor.close();
		return programs;
	}

	/**
	 * 从网络解析节目分类
	 * 
	 * @param result
	 * @return
	 */
	private static ArrayList<ProgramItemBean> paserProgramItem(
			InputStream result) {
		ArrayList<ProgramItemBean> items = null;
		ProgramItemBean fitem = null;
		XmlPullParser parser = Xml.newPullParser();

		try {
			parser.setInput(result, "UTF-8");
			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {

				switch (eventType) {

				case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
					items = new ArrayList<ProgramItemBean>();
					break;
				case XmlPullParser.START_TAG:// 开始元素事件
					if ("fitem".equals(parser.getName())) {
						fitem = new ProgramItemBean();
					} else if ("epgNode".equals(parser.getName())) {
						String node = parser.nextText();
						fitem.setNode(Integer.valueOf(node));
						// SLog.d(TAG, fitem.getNode() + "");

					} else if ("epgName".equals(parser.getName())) {
						String epgName = parser.nextText();
						fitem.setName(epgName);
						// SLog.d(TAG, fitem.getName());
					} else if ("epgPNode".equals(parser.getName())) {
						String epgPNode = parser.nextText();
						fitem.setPnode(Integer.valueOf(epgPNode));
						// SLog.d(TAG, fitem.getPnode() + "");
					}

					break;
				case XmlPullParser.END_TAG:// 结束元素事件
					if ("fitem".equals(parser.getName()) && fitem != null) {
						items.add(fitem);
					}
					break;

				}
				eventType = parser.next();
			}
		} catch (Exception e) {
			SLog.d(TAG, e.toString());
			return null;
		} finally {
			try {
				if (result != null) {
					result.close();
				}
			} catch (IOException e) {
				SLog.d(TAG, e.toString());
			}
		}
		return items;
	}

	/**
	 * 从网络解析指定频道下的类表
	 * 
	 * @param result
	 */
	private static ArrayList<ProgramBean> paserProgram(InputStream result) {

		XmlPullParser parser = Xml.newPullParser();
		ProgramBean pInfo = null;
		ArrayList<ProgramBean> programs = null;
		try {
			parser.setInput(result, "UTF-8");
			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {

				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
					programs = new ArrayList<ProgramBean>();
					break;
				case XmlPullParser.START_TAG:// 开始元素事件
					if ("program".equals(parser.getName())) {
						pInfo = new ProgramBean();

					} else if (pInfo != null) {
						if ("pid".equals(parser.getName())) {
							String pid = parser.nextText();
							pInfo.setPid(pid);
							SLog.d(TAG, "节目标识==" + pInfo.getPid());

						} else if ("pweekday".equals(parser.getName())) {
							String pweekday = parser.nextText();
							pInfo.setPweekday(Integer.valueOf(pweekday));
							SLog.d(TAG, "节目在哪周播放==" + pInfo.getPweekday());

						} else if ("pstime".equals(parser.getName())) {
							String pstime = parser.nextText();
							pInfo.setPstime(pstime);
							SLog.d(TAG, "节目的开始时间==" + pInfo.getPstime());

						} else if ("pftime".equals(parser.getName())) {
							String pftime = parser.nextText();
							pInfo.setPftime(pftime);
							SLog.d(TAG, "节目的播放的结束时间==" + pInfo.getPftime());

						} else if ("pn".equals(parser.getName())) {
							String pn = parser.nextText();
							pInfo.setPn(pn);
							SLog.d(TAG, "节目名字==" + pInfo.getPn());

						} else if ("cname".equals(parser.getName())) {
							String cname = parser.nextText();
							pInfo.setCname(cname);
							SLog.d(TAG, "频道名字==" + pInfo.getCname());

						} else if ("cid".equals(parser.getName())) {
							String cid = parser.nextText();
							pInfo.setCid(new Integer(cid));
							SLog.d(TAG, "频道号==" + pInfo.getCid());

						} else if ("epgid".equals(parser.getName())) {
							String epgid = parser.nextText();
							pInfo.setEpgid(epgid);
							SLog.d(TAG, "getEpgid==" + pInfo.getEpgid());

						} else if ("ptype".equals(parser.getName())) {
							String ptype = parser.nextText();
							pInfo.setPtype(ptype);
							SLog.d(TAG, "节目类型==" + pInfo.getPtype());
						} else if ("precommend".equals(parser.getName())) {
							String precommend = parser.nextText();
							pInfo.setPrecommend(precommend);
							SLog.d(TAG, "precommend==" + pInfo.getPrecommend());
						} else if ("pictype".equals(parser.getName())) {
							pInfo.setPictype(parser.nextText());

						} else if ("picurl".equals(parser.getName())) {
							String url = parser.nextText();
//							url = "http://haier:8080/ECServer_H/image/120.jpg";
							url ="http://127.0.0.1:8080/ECServer_H/image/test.jpg";
							pInfo.setPicurl(url);
							SLog.d(TAG, "节目图片路径==" + pInfo.getPicurl());
						} else if ("spicrul".equals(parser.getName())) {
							pInfo.setSpicurl(parser.nextText());
							SLog.d(TAG,
									"节目图片路径setSpicurl==" + pInfo.getSpicurl());
						} else if ("fid".equals(parser.getName())) {
							String fid = parser.nextText();
							pInfo.setFid(fid);
							SLog.d(TAG, "getFid==" + pInfo.getFid());
						} else if ("fid2".equals(parser.getName())) {
							String fid2 = parser.nextText();
							pInfo.setFid2(fid2);
							SLog.d(TAG, "getFid2==" + pInfo.getFid2());
						}
					}

					break;
				case XmlPullParser.END_TAG:// 结束元素事件
					if ("program".equals(parser.getName()) && pInfo != null) {
						programs.add(pInfo);
					}
					break;
				}
				eventType = parser.next();
			}
		} catch (Exception e) {
			SLog.d(TAG, e.toString());
			return null;
		} finally {
			try {
				if (result != null) {
					result.close();
				}
			} catch (IOException e) {
				SLog.d(TAG, e.toString());
			}
		}
		SLog.d(TAG, "解析节目完毕，长度为，不加任何过滤：" + programs.size());
		return programs;

	}

	// 根据时间和频道号得节目

	/**
	 * 解析频道logo的方法
	 * 
	 * @param result
	 * @return
	 */
	private static ArrayList<ChannelLogoBean> paserChannelLogo(
			InputStream result) {

		ArrayList<ChannelLogoBean> bit_pics = null;
		ChannelLogoBean bit_pic = null;
		XmlPullParser parser = Xml.newPullParser();
		try {
			parser.setInput(result, "UTF-8");
			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					bit_pics = new ArrayList<ChannelLogoBean>();
					break;
				case XmlPullParser.START_TAG:
					if ("item".equals(parser.getName())) {
						bit_pic = new ChannelLogoBean();
					} else if ("cid".equals(parser.getName())) {
						bit_pic.setCid(parser.nextText());
						SLog.d(TAG, "频道编号为=====" + bit_pic.getCid());
					} else if ("cname".equals(parser.getName())) {
						bit_pic.setCname(parser.nextText());
						SLog.d(TAG, "频道名称为=====" + bit_pic.getCname());
					} else if ("logourl".equals(parser.getName())) {
						bit_pic.setLogourl(parser.nextText());
						SLog.d(TAG, "频道台标路径为=====" + bit_pic.getLogourl());
					}
					break;
				case XmlPullParser.END_TAG:
					if (bit_pic != null && "item".equals(parser.getName())) {
						bit_pics.add(bit_pic);
					}
					break;
				}
				eventType = parser.next();
			}
		} catch (XmlPullParserException e) {

			SLog.e("", e.toString());
		} catch (IOException e) {

			SLog.e("", e.toString());
		}
		return bit_pics;
	}

	/**
	 * 解析频道图片的方法
	 * 
	 * @param result
	 * @return
	 */
	private static ArrayList<ChannelPIPBean> paserChannelPIP(InputStream result) {

		ArrayList<ChannelPIPBean> bit_pics = null;
		ChannelPIPBean bit_pic = null;
		XmlPullParser parser = Xml.newPullParser();
		try {
			parser.setInput(result, "UTF-8");
			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					bit_pics = new ArrayList<ChannelPIPBean>();
					break;
				case XmlPullParser.START_TAG:
					if ("img".equals(parser.getName())) {
						bit_pic = new ChannelPIPBean();
					} else if ("id".equals(parser.getName())) {
						bit_pic.setId(parser.nextText());
						SLog.d(TAG, "图片id为=====" + bit_pic.getId());
					} else if ("url".equals(parser.getName())) {
						bit_pic.setBitmap_url(parser.nextText());
						SLog.d(TAG, "图片url为=====" + bit_pic.getBitmap_url());

					}
					break;
				case XmlPullParser.END_TAG:
					if (bit_pic != null && "img".equals(parser.getName())) {
						bit_pics.add(bit_pic);
					}
					break;
				}
				eventType = parser.next();
			}
		} catch (XmlPullParserException e) {

			SLog.e("", e.toString());
		} catch (IOException e) {

			SLog.e("", e.toString());
		}
		SLog.d(TAG, "解析出的截图长度为" + bit_pics.size());
		return bit_pics;
	}

	/**
	 * 用时间进行过滤
	 * 
	 * @param arrayList
	 * 
	 * @return ArrayList<ProgramBean>
	 * @throws Exception
	 */
	private static ArrayList<ProgramBean> programTimeFilters(
			ArrayList<ProgramBean> arrayList) {
		// 拿到后按时间先过滤下
		ArrayList<ProgramBean> filters_time = new ArrayList<ProgramBean>();

		SLog.d(TAG, "当前系统周数=========" + week);
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");

		// 得到当前系统时间，并转换成long类型
		String str = df.format(new Date());
		SLog.d(TAG, "当前系统时间========" + str);

		for (int i = 0; i < arrayList.size(); i++) {
			SLog.d(TAG, "按时间过滤的节目播放结束时间========" + arrayList.get(i).getPftime());
			SLog.d(TAG, "当前节目所在频道========" + arrayList.get(i).getCid());
			SLog.d(TAG, "当前节目的唯一标识========" + arrayList.get(i).getPid());
			SLog.d(TAG, "当前节目名称========" + arrayList.get(i).getPn());
			try {
				// 得到节目播放的开始时间,并转换成long类型
				String time = arrayList.get(i).getPstime();
				long ptime = df.parse(time).getTime();
				// 得倒节目播放的结束时间
				String ltime = arrayList.get(i).getPftime();
				long pltime = df.parse(ltime).getTime();

				// 当前时间
				long current_time = df.parse(str).getTime();
				// 得倒节目的周数
				int p_week = arrayList.get(i).getPweekday();

				// 按时间过滤方法1
				if ( pltime > current_time&&week == p_week ||(week+1)==p_week) {
					filters_time.add(arrayList.get(i));
				}
			} catch (ParseException e) {
				SLog.d(TAG, e.toString());
			}
		}
		SLog.d(TAG, "按时间过滤长度：" + filters_time.size());
		return filters_time;
	}

	/**
	 * 按节目属性过滤
	 * 
	 * @param context
	 * 
	 * @param filters_time
	 * @return
	 */
	private static ArrayList<ProgramBean> programAttriFilters(Context context,
			ArrayList<ProgramBean> filters_time) {
		// 在过滤之前需要获取节目的分类把他存起来
		int[] p_item = null;
		if (getProgramItem(context).size() > 0) {
			ArrayList<ProgramItemBean> items = getProgramItem(context);
			p_item = new int[items.size()];
			for (int i = 0; i < items.size(); i++) {
				p_item[i] = items.get(i).getNode();
			}

		}

		// 按属性过滤每一个节目
		ArrayList<ProgramBean> programGrouped = new ArrayList<ProgramBean>();
		if (filters_time != null) {
			SLog.d(TAG, "我已经得倒节目不为空了");
		} else {
			SLog.d(TAG, "节目得不到了！！");
		}
		for (int i = 0; i < filters_time.size(); i++) {
			String p_type = filters_time.get(i).getPtype();
			if (p_type != null && p_type.trim().length() > 0) {
				String[] sArray = p_type.split(",");
				// 节目属性的集合
				int[] pros = new int[sArray.length];
				for (int j = 0; j < sArray.length; j++) {
					// 测试equals，在测试==,目的把空格去掉
					if (sArray[j] != null && sArray[j].trim().length() > 0) {
						pros[j] = Integer.valueOf(sArray[j]);
					}
				}

				// 将节目属性和节目分类比较
				// 什么情况下将节目加入programGrouped这里？每个节目的属性和得倒的预置节目属性比较，只要相同就取
				for (int j = 0; j < pros.length; j++) {
					for (int j2 = 0; j2 < p_item.length; j2++) {
						if (pros[j] == p_item[j2]
								&& !programGrouped
										.contains(filters_time.get(i))) {
							programGrouped.add(filters_time.get(i));
						}
					}
				}

			}
		}
		return programGrouped;

	}
}